package com.azzaou.util;

import java.io.IOException;

import javax.faces.context.FacesContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;


/**
 * SessionFilter
 */
public class SessionFilter implements Filter
{
  /**
   * logger of class
   */
  private static final Logger logger = Logger
			.getLogger(SessionFilter.class);
  
  /**
   * WebApplicationContext
   */
  WebApplicationContext springContext;
  
  /**
   * doFilter
   * 
   * @param request
   *          :request
   * @param response
   *          : response
   * @param chain
   *          :chain
   * @throws IOException
   *           : IOException
   * @throws ServletException
   *           :ServletException
   */
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException
  {
    HttpServletRequest req = (HttpServletRequest)request;
    HttpServletResponse res = (HttpServletResponse)response;
    HttpSession session = req.getSession();
    if (session != null)
    {
      if ("success".equals(session.getAttribute("authenticated")))
      {
    	  chain.doFilter(request, response);
      }
      else
      {
        logger.debug("Forward to login.jsf");
        res.sendRedirect(req.getContextPath() + "/login.jsf");
        return;
      }
    }
    else
    {
      FacesContext.getCurrentInstance().getExternalContext()
          .redirect(req.getContextPath() + "/login.jsf");
    }
  }


  @Override
  public void destroy()
  {
    logger.info("destroy the filter ...");
  }


  @Override
  public void init(FilterConfig filterConfig) throws ServletException
  {
  }

}